#%%
# https://www.liaoxuefeng.com/wiki/1016959663602400/1017790702398272
# smtp发送邮件

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from email.utils import parseaddr, formataddr, formatdate
import smtplib
import MailConfig
import os

#%%
class EmailSender():
    def __init__(self, mail_provider: str,mail_config: MailConfig.MailConfig):
        self.__mail_config = mail_config
        self.__provider = mail_provider
    
    def connect(self):
        if self.__mail_config.ssl_smtp_port is not None:
            self.__server = smtplib.SMTP_SSL(self.__mail_config.smtp_server, self.__mail_config.ssl_smtp_port)
        elif self.__mail_config.unssl_smtp_port is not None:
            self.__server = smtplib.SMTP(self.__mail_config.smtp_server, self.__mail_config.unssl_smtp_port)
        else:
            self.__server = smtplib.SMTP(self.__mail_config.smtp_server)

        self.__server.login(self.__mail_config.user, self.__mail_config.passwd)

    def __attach(self, file_path: str):
        '''
        file_paths必须是list格式
        '''
        with open(file_path, 'rb') as f:
            app = MIMEApplication(f.read(), Name=os.path.basename(file_path))
        return app

    def __format_addr(self, name, addr):
        return formataddr((Header(name, 'utf-8').encode('utf-8'), addr))

    def send(self, to_emails: list, msg: str, attachment_files_path: list):
        '''
        to_emails: 需要发送到的email地址
        '''
        # 1. 构造header
        full_msg = MIMEMultipart()
        full_msg['Subject'] = "21级硕士1班团支部-青年大学习"
        full_msg['From'] = self.__format_addr("21级硕士1班团支部", self.__mail_config.user)
        full_msg['Date'] = formatdate(localtime=True)

        # 2. 构造内容
        content = MIMEText(msg, 'plain', 'utf-8')
        full_msg.attach(content)

        # 3. 添加附件
        for i in attachment_files_path:
            if os.path.exists(i):
                full_msg.attach(self.__attach(i))

        self.__server.sendmail(self.__mail_config.user, to_emails, full_msg.as_string())


    def quit(self):
        self.__server.quit()


# %%
